package cn.fzkj.project.system.controller;

import cn.fzkj.common.utils.ServletUtils;
import cn.fzkj.common.utils.StringUtils;
import cn.fzkj.common.utils.file.FileUtils;
import cn.fzkj.common.utils.poi.ExcelUtil;
import cn.fzkj.framework.config.RuoYiConfig;
import cn.fzkj.framework.mail.MailEntity;
import cn.fzkj.framework.messagequece.MessageType;
import cn.fzkj.framework.messagequece.service.MessageService;
import cn.fzkj.framework.security.service.TokenService;
import cn.fzkj.framework.web.domain.ResultVO;
import cn.fzkj.project.system.domain.SysTodo;
import cn.fzkj.project.system.domain.SysUser;
import cn.fzkj.project.system.service.ISysTodoService;
import cn.fzkj.project.system.service.ISysUserService;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/** 待办事项 */
@RestController
@RequestMapping(value = "todo")
public class SysTodoController {

    private Logger log = LoggerFactory.getLogger(SysTodoController.class);

    /** 邮件发送人 */
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private ISysTodoService todoService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private TokenService tokenService;

    /** 通过日期查询 */
    @RequestMapping(value = "selectListByDate", method = RequestMethod.GET)
    public ResultVO selectListByDate(String date, Long userId){
        return ResultVO.success(todoService.selectTodosByDate(date, userId));
    }

    /** 新增 */
    @RequestMapping(value = "insertTodo", method = RequestMethod.POST)
    public ResultVO insertTodo(@RequestBody SysTodo todo){
        System.out.println(todo);
        return ResultVO.success(todoService.insertTodo(todo));
    }

    /** 更新状态 */
    @RequestMapping(value = "updateTodoStatus", method = RequestMethod.POST)
    public ResultVO updateTodoStatus(@RequestBody SysTodo todo){
        System.out.println(todo);
        return ResultVO.success(todoService.updateTodoStatus(todo));
    }

    /** 通过id删除 */
    @RequestMapping(value = "deletedById", method = RequestMethod.DELETE)
    public ResultVO deletedById(Long tId, Long userId){
        return ResultVO.success(todoService.deleteTodoById(tId, userId));
    }

    /** 批量删除 */
    @RequestMapping(value = "batchDelByIds", method = RequestMethod.DELETE)
    public ResultVO batchDelByIds(Long[] ids, Long userId){
        return ResultVO.success(todoService.batchDelTodos(ids, userId));
    }

    /** 批量插入 */
    @RequestMapping(value = "batchInsert", method = RequestMethod.POST)
    public ResultVO batchInsert(@RequestBody List<SysTodo> todos){
        return ResultVO.success(todoService.batchInsertTodos(todos));
    }

    /** 查询未完成 */
    @RequestMapping(value = "selectListUnDone", method = RequestMethod.GET)
    public ResultVO selectListUnDone(@RequestParam(value = "category", required = false) String category){
        Long userId = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId();
        return ResultVO.success(todoService.selectListUnDone(category, userId));
    }

    /** 查询完成 */
    @RequestMapping(value = "selectListDone", method = RequestMethod.GET)
    public ResultVO selectListDone(@RequestParam(value = "category", required = false) String category){
        Long userId = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId();
        return ResultVO.success(todoService.selectListDone(category, userId));
    }

    /** 查询数量 */
    @RequestMapping(value = "selectListCount", method = RequestMethod.GET)
    public ResultVO selectListCount(@RequestParam(value = "category", required = false) String category){
        Long userId = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId();
        return ResultVO.success(todoService.selectListCount(userId));
    }

    /** 导出到邮箱 */
    @RequestMapping(value = "export", method = RequestMethod.GET)
    public void export(SysTodo todo) {
        try {
            List<SysTodo> list = todoService.selectList(todo);
            SysUser sysUser = userService.selectUserById(todo.getUserId());
            ExcelUtil<SysTodo> util = new ExcelUtil<SysTodo>(SysTodo.class);
            ResultVO todoData = util.exportExcel(list, sysUser.getUserName() + "_TODO");
            String fileName = (String) todoData.get("msg"); // 附件名称
            if (!FileUtils.isValidFilename(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            // 获取文件地址
            String filePath = RuoYiConfig.getDownloadPath() + fileName;
            // 发送rabbitmq消息到邮箱
            /// 构建邮件对象
            MailEntity entity = new MailEntity.MailBuilder()
                    .subject("EVERYDAY")
                    .from("EVERYDAY" + "<" + from + ">")
                    .to(sysUser.getEmail())
                    .filePath(filePath)
                    .sentDate(new Date())
                    .enclosureName(fileName)
                    .text("亲爱的EVERYDAY用户：\n" +
                            "您的TODO数据已导出，详情请查看附件！\n" +
                            "有任何问题可直接通过以下方式联系我们:\n" +
                            "电话：400-***-7707\n" +
                            "QQ：*******\n" +
                            "微信客服：******\n" +
                            "祝您生活愉快 :)")
                    .build();
            messageService.sendMailMime(new Gson().toJson(entity));
        } catch (Exception e) {
            log.error("导出文件失败", e);
        }
    }

}
